package com.opdar.seed.idoc.services;

import com.opdar.framework.db.interfaces.IDao;
import com.opdar.framework.db.interfaces.IDatabase;
import com.opdar.framework.web.SeedWeb;
import com.opdar.framework.web.anotations.Component;
import com.opdar.framework.web.anotations.Inject;
import com.opdar.seed.idoc.beans.ProjectEntity;
import com.opdar.seed.idoc.beans.ShareVarEntity;

import java.sql.Timestamp;
import java.util.List;

/**
 * Created by ���� on 2015/8/21.
 */
@Component
public class ProjectService {

    @Inject
    IDatabase database;

    public ProjectEntity create(String projectName) {
        ProjectEntity project = new ProjectEntity();
        project.setProjectName(projectName);
        project.setCreateTime(new Timestamp(System.currentTimeMillis()));
        IDao<ProjectEntity> projectDao = database.getDao(ProjectEntity.class);
        if (projectDao.insert(project).end().status() > 0) {
            project = projectDao.select().where("project_name",projectName).WhereEND().end().findOne();
            return project;
        }
        return null;
    }
    public ProjectEntity findById(String projectId) {
        IDao<ProjectEntity> projectDao = database.getDao(ProjectEntity.class);
        ProjectEntity project = projectDao.select().where("id",projectId).WhereEND().end().findOne();
        return project;
    }

    public List<ShareVarEntity> findShareVars(String projectId) {
        IDao<ShareVarEntity> shareVarDao = database.getDao(ShareVarEntity.class);
        List<ShareVarEntity> list = shareVarDao.select().where("project_id",projectId).WhereEND().end().findAll();
        return list;
    }

    public boolean insertShareVar(ShareVarEntity sharevar) {
        IDao<ShareVarEntity> shareVarDao = database.getDao(ShareVarEntity.class);
        return shareVarDao.insert(sharevar).end().status()>0;
    }
    public boolean delShareVar(String id) {
        IDao<ShareVarEntity> shareVarDao = database.getDao(ShareVarEntity.class);
        return shareVarDao.delete().where("id",id).WhereEND().end().status()>0;
    }

    public boolean switchDecoder(String decoder) {
        String projectId = (String) SeedWeb.SharedRequest().get().getSession().getValue("projectId");
        IDao<ProjectEntity> projectDao = database.getDao(ProjectEntity.class);
        ProjectEntity o = new ProjectEntity();
        o.setDecoder(decoder);
        return projectDao.update(o).where("id",projectId).WhereEND().end().status()>0;
    }
}
